<?php

use think\db;

// 异常错误报错级别,
error_reporting(E_ERROR | E_PARSE);

function C($name)
{
    $config = cache('systemConfig');
    if ($config) {
        $value = '';
        foreach ($config as &$v) {
            if ($v['name'] == $name) {
                $value = $v['output_value'];
                break;
            }
        }

        return $value;
    } else {
        return '';
    }
}

/**
 * 系统加密方法
 * @param string $data   要加密的字符串
 * @param int    $expire 过期时间 (单位:秒)
 * @return string
 */
function thinkEncrypt($data, $expire = 0)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @return string
 */
function thinkDecrypt($data)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $x = 0;
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }

    return base64_decode($str);
}

/**
 * 检查验证码
 * */
function checkVerify($code)
{
    $verify = new \think\captcha\Captcha();

    return $verify->check($code);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } else if (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return true;
    }

    return false;
}

/**
 * 获取域名前缀
 * */
function getHost()
{
    $res = is_ssl();
    if ($res) {
        return 'https://' . $_SERVER['HTTP_HOST'];
    } else {
        return 'http://' . $_SERVER['HTTP_HOST'];
    }
}

/**
 * 按综合方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiReturn($result, $msg = '', $data = false)
{
    if (!is_numeric($result)) {
        return '';
    }

    return apiJson($result, $msg, $data);
}

/**
 * 流程分组排序
 */
function processToGroupSort($processFLows)
{
    $__processResult = [];
    foreach ($processFLows as $key => $value) {
        if (!isset($__processResult[$value['number_of_submissions']])) {
            $__processResult[$value['number_of_submissions']] = ['group' => $value['number_of_submissions'], 'list' => []];
        }
        $__processResult[$value['number_of_submissions']]['list'][] = $value;
    }
    foreach ($__processResult as $key => $value) {
        $__processResult[$key]['list'] = arraySort($value['list'], 'id', SORT_ASC);
    }
    sort($__processResult);
    return $__processResult;
}

/**
 * 二维数组根据某个字段排序
 * @param array  $array 要排序的数组
 * @param string $keys  要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC)
{
    if (!$array) {
        return null;
    }
    $keysValue = [];
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}

/**
 * 按json方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiJson($result, $msg = '', $data = false)
{

    if (!is_numeric($result)) {
        return '';
    }

    if ($data > 0 || $data === []) {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? $data : []
        ];
    } else {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? $data : ''
        ];
    }

    echo json_encode($message);
    exit;
}


/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
    if (preg_replace('/\D/s', '', $id) == $id) {
        //ID
        $info = Db::name('picture')->field('path')->where(['id' => $id])->find();
        if ($info) {
            return getHost() . $info['path'];
        } else {
            return '';
        }
    } else {
        //路径
        return $id;
    }
}

/**
 * 用户头像处理
 * @param int $avatar_id 用户头像ID 或 用户头像路径
 * @return string
 * */
function doAvatar($avatar_id)
{
    if (strlen($avatar_id) < 10) {
        //此时用户头像为修改之后的头像
        $avatar = getPicture($avatar_id);
    } else {
        $avatar = $avatar_id;
    }

    return $avatar ? : '';
}

/**
 * 一维数组去重
 * */
function a_array_unique($array)
{
    $out = [];
    foreach ($array as $key => $value) {
        if (!in_array($value, $out)) {
            $out[$key] = $value;
        }
    }
    return $out;
}

/**
 *获取access_tokenA
 *  */
function get_access_token()
{
    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(get_php_file("access_token.json"));
    if ($data->expires_time < time()) {
        // 如果是企业号用以下URL获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx14f0e22861952e28&secret=11dd50a502bdb002860bf494e1e78d72";
        $access_token_json = httpsRequest($url);
        $access_token = json_decode($access_token_json, true);
        if ($access_token) {
            $data->expires_time = time() + 7000;
            $data->access_token = $access_token;
            set_php_file("access_token.json", json_encode($data));
        }
        $access_token = $access_token['access_token'];
    } else {
        $access_token = $data->access_token->access_token;
    }
    return $access_token;
}

function get_php_file($filename)
{
    if (!is_file(RUNTIME_PATH . '/' . $filename)) {
        $data['expires_time'] = 0;
        $data['jsapi_ticket'] = '';
        set_php_file($filename, json_encode($data));
    }
    return file_get_contents(RUNTIME_PATH . '/' . $filename);
}

function set_php_file($filename, $content)
{
    file_put_contents(RUNTIME_PATH . '/' . $filename, $content);
}

function httpsRequest($url, $data = null, $header = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    if (!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 发送微信公众号模板消息
 * @param string $openid 公众号openid
 * @param array  $msg    消息内容
 * @param string $type   消息类型：1：直推比例分佣，2：级差比例分佣，3：服务津贴，4：购物收益抵扣，5：收益提现，6：销售奖励月结，7：退休基金月结，8：收益提现失败返还收益，9：区域门店补贴月结，10：奖励收益，11，惩罚收益
 * @param string $path   小程序路径
 * */
function sendWxTemplateNotice($openid, $msg, $type, $page = '')
{
    $access_token = get_access_token();

    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;


    $template_id = 'rdrFT83yHHpPcRvPVCoc9KM5QVsH6BqWrljhyw5sqjk';


    $data = [
        'touser' => $openid,
        'template_id' => $template_id,
        'topcolor' => '#FF0000',
        'data' => $msg
    ];

    if ($page) {
        $data['miniprogram']['appid'] = C('XCX_APPID');
        $data['miniprogram']['pagepath'] = $page;
    }


    $data = json_encode($data, JSON_UNESCAPED_UNICODE);

    httpsRequest($url, $data);
}

function api($name, $vars = [])
{
    $array = explode('/', $name);
    $method = array_pop($array);
    $classname = array_pop($array);
    $module = $array ? array_pop($array) : 'Common';
    $callback = $module . '\\Api\\' . $classname . 'Api::' . $method;
    if (is_string($vars)) {
        parse_str($vars, $vars);
    }

    return call_user_func_array($callback, $vars);
}

/**
 * workerman
 * 获取后台用户列表用户最新的消息时间
 * @param int $user_id 用户id
 * @return string
 * */
function getUserNewMsgTime($user_id)
{
    $create_time = Db::name('chat')
        ->where(['from_uid' => $user_id])
        ->whereOr(
            function ($query) use ($user_id) {
                $query->where(['to_uid' => $user_id]);
            }
        )
        ->order('create_time desc')
        ->value('create_time');

    return $create_time ? date('H:i:s', $create_time) : '';
}

/**
 * 返回字符串的毫秒数时间戳
 **/
function getMillisecond()
{
    $time = explode(" ", microtime());
    $time = $time [1] . ($time [0] * 1000);
    $time2 = explode(".", $time);
    $time = $time2 [0];
    return $time;
}

/**
 * 发送钉钉消息通知
 * @param string $access_token access_token
 * @param int    $agent_id     应用的agentid
 * @param string $template_id  消息模板id
 * @param string $userid_list  接收者的用户userid列表
 * @param string $data         消息数据
 * */
function sendDDMsg($access_token, $agent_id, $template_id, $userid_list, $data)
{
    $url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate';

    $url = $url . '?access_token=' . $access_token;

    $info = [
        'agent_id' => $agent_id,
        'template_id' => $template_id,
        'userid_list' => $userid_list,
        'data' => $data
    ];

    $header[] = 'content-type: application/json';
    httpsRequest($url, json_encode($info, JSON_UNESCAPED_UNICODE), $header);
}


/**
 * 获取抄送人姓名集合
 * @param int $id app_form表主键id
 * @return string
 * */
function getCarbonUsername($id)
{
    $carbon_auth_list = Db::name('carbon_auth c')
        ->join('tp_user u1', 'c.carbon_uid = u1.id', 'left')
        ->join('tp_user u2', 'c.get_uid = u2.id', 'left')
        ->field('u1.username carbon_username,u2.username get_username')
        ->where(['c.form_id' => $id, 'c.is_auth' => 1])
        ->select();

    if ($carbon_auth_list) {
        $carbon_username_list = array_column($carbon_auth_list, 'carbon_username');
        $get_username_list = array_column($carbon_auth_list, 'get_username');
        $list = array_filter(array_unique(array_merge($carbon_username_list, $get_username_list)));
        return implode(',', $list);
    } else {
        return '';
    }
}

/**
 * 获取审核人姓名集合
 * @param int $id app_form表主键id
 * @return string
 * */
function getApprovalUsername($id)
{
    $approval_list = Db::name('approval_process a')
        ->join('tp_user u', 'a.uid = u.id', 'left')
        ->field('u.username')
        ->where(['a.form_id' => $id, 'a.is_obsolete' => 1])
        ->select();

    if ($approval_list) {
        return implode(',', array_column($approval_list, 'username'));
    } else {
        return '';
    }
}

/**
 * 格式化时间
 * @param int  $time 时间戳
 * @param date $date 时间格式
 * */
function timeFormat($time, $date = 'Y-m-d H:i:s')
{
    if ($time) {
        return date($date, $time);
    } else {
        return '';
    }
}
